package demo1;

import java.util.Arrays;

public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int value) {
            this.key = key;
            this.val = value;
        }
    }

    public Node[] array;
    public int usedSize;

    //负载因子 设置为0.7
    public static final double loadFactor = 0.7;

    public HashBuck() {
        this.array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
            }
            cur = cur.next;
        }
        Node newNode = new Node(key,val);
        newNode.next = array[index];
        array[index] = newNode;
        usedSize++;
        //如果负载因子 大于0.7那就扩容数组
        if (calculateLoadFactor() >= loadFactor) {
            //扩容
            resize();
        }
    }
    //扩容
    private void resize() {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            Node curNext = null;
            while (cur != null) {
                curNext = cur.next;
                int index = cur.key % newArray.length; //找到了在新数组当中的位置
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    //计算负载因子
    public double calculateLoadFactor() {
        return (usedSize*1.0) / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
